*Get region codes*

*Load data*
clear
use "Data\Core_datasets\sample_04_thesis.dta"

*Initial steps*
compress, nocoalesce
sort pnr aar

*Age restrictions*
gen age=alder
destring age, replace
keep if age>=19 & age<=60

*Keep only necessary variables*
keep pnr aar bopael_kom_kode

*Map municipality codes backwards*
gen new_municipality=bopael_kom_kode if aar==2006
gen old_municipality=bopael_kom_kode if aar==2005

by pnr: egen all_new_municipality=mode(new_municipality), maxmode
by pnr: egen all_old_municipality=mode(old_municipality), maxmode

by all_old_municipality, sort: egen old_to_new=mode(all_new_municipality), maxmode

frame copy default reduced

frame change reduced

collapse (first) old_to_new, by(all_old_municipality)

drop if all_old_municipality==""

gen number=_n

destring all_old_municipality, replace
destring old_to_new, replace

forvalues i=1(1)319{

qui sum all_old_municipality if number==`i'
sca old_`i'=r(mean)
qui sum old_to_new if number==`i'
sca old_to_new_`i'=r(mean) 	
	
}

frame change default

sort pnr aar

destring bopael_kom_kode, replace

gen municipality_updated=bopael_kom_kode if aar>=2006

forvalues i=1(1)319{

replace municipality_updated=old_to_new_`i' if aar<=2005 & bopael_kom_kode==old_`i'
	
}


*Make region variable*
gen region=.
replace region=81 if inlist(municipality_updated, 773, 787, 810, 813, 820, 825, 840, 846, 849, 851, 860)
replace region=82 if inlist(municipality_updated, 615, 657,	661, 665, 671, 706, 707, 710, 727, 730, 740, 741, 746, 751, 756, 760, 766, 779, 791)
replace region=83 if inlist(municipality_updated, 410, 420,	430, 440, 450, 461, 479, 480, 482, 492, 510, 530, 540, 550, 561, 563, 573, 575, 580, 607, 621, 630)
replace region=84 if inlist(municipality_updated, 101, 147, 151, 153, 155, 157, 159, 161, 163, 165, 167, 169, 173, 175, 183, 185, 187, 190, 201, 210, 217, 219, 223, 230, 240, 250, 260, 270, 400, 411)
replace region=85 if inlist(municipality_updated, 253, 259, 265, 269, 306, 316, 320, 326, 329, 330, 336, 340, 350, 360, 370, 376, 390)

*Finish up*
drop new_municipality old_municipality all_new_municipality all_old_municipality old_to_new
drop bopael_kom_kode

tostring municipality_updated, replace
tostring region, replace

**Save**
save "Data\regions.dta", replace


